package ast.stmt;

import icg.EQLabel;
import icg.Quadruple;
import ts.SymbolTable;
import ast.Node;
import ast.exp.Expression;
import ast.type.Type;

public class IfStmt extends Statement {
	private Expression exp;
	private Statement se;
	private Statement senao;
	public EQLabel trueL;// = EQLabel.FALL;
	public EQLabel falseL;// = EQLabel.FALL;

	public IfStmt(Expression exp, Statement se, Statement senao) {
		this.exp = exp;
		this.se = se;
		this.senao = senao;
	}

	@Override
	public String toString() {
		return "<IfStmt>\n" + "<exp>" + exp + "\n</exp>\n" + "<se>\n" + se
				+ "\n</se>\n" + "<senao>\n" + senao + "\n</senao>\n"
				+ "</IfStmt>";
	}

	@Override
	public void typeCheck(Type type) {
		Type typeExp = exp.typeCheck();
		if (typeExp != Type.ERROR && typeExp != Type.BOOLEAN) {
			System.out.println("invalid type expression in condition");
			SymbolTable.errors++;
		}
		se.typeCheck(type);
		senao.typeCheck(type);
	}

	@Override
	public Boolean isReturned() {
		return (se.isReturned() && senao.isReturned());
	}

	@Override
	public Boolean hasCtrlFlow() {
		return se.hasCtrlFlow() || senao.hasCtrlFlow();
	}

	@Override
	public void genCode() {
		exp.trueL = EQLabel.FALL;
		exp.falseL = new EQLabel();
		EQLabel l = (this.next.equals(EQLabel.FALL)) ? new EQLabel(): this.next;
		senao.next = l;
		se.next = l;

		exp.genCode();
		se.genCode();
		
		Node.icg.gen(Quadruple.jump(se.next));
		EQLabel.useLabel(exp.falseL);

		senao.genCode();

		if (this.next.equals(EQLabel.FALL)) {
			EQLabel.useLabel(se.next);
		}

	}
}
